//
//  FiltrateRightView.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/12/15.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "FiltrateRightView.h"
// model
#import "FiltrateFirstModel.h"
#import "FiltrateSecondModel.h"
// view
#import "FiltrateSectionTitleView.h"
#import "FiltratePriceTextCell.h"
#import "FiltrateAttributeItemCell.h"

@interface FiltrateRightView () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UIView *mainView;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIButton *completeButton;
@property (nonatomic, strong) UIButton *resetButton;

//@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) FiltratePriceTextCell *textCell;
@property (nonatomic, strong) GoodsListFiltrateRightModel *rightModel;
@end

@implementation FiltrateRightView

- (instancetype)initWithRightModel:(GoodsListFiltrateRightModel *)model block:(void (^)(GoodsListFiltrateRightModel *rightModel))block {
    self = [self initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.block = block;
        self.rightModel = model;
    }
    return self;
}

- (void)showFromRight {
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    if (!window) {
        window = [[UIApplication sharedApplication].windows lastObject];
    }
    [window addSubview:self];
    [window bringSubviewToFront:self];
    [self showAnimation];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
//        _dataSource = [NSMutableArray array];
//        _dataSource = [self configureTestData];
        _textCell = [[[NSBundle mainBundle] loadNibNamed:@"FiltratePriceTextCell" owner:self options:nil] firstObject];
        _textCell.minTextField.delegate = self;
        _textCell.maxTextField.delegate = self;
        _rightModel = [[GoodsListFiltrateRightModel alloc] init];
        [self configureUI];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.mainView.frame = self.bounds;
    self.backView.frame = CGRectMake(self.width - 280, 0, 280, self.height);
    self.tableView.frame = CGRectMake(0, 0, self.backView.width, self.backView.height-49);
    self.resetButton.frame = CGRectMake(0, self.height - 49, self.backView.width * 0.5, 49);
    self.completeButton.frame = CGRectMake(self.resetButton.right, self.height - 49, self.backView.width * 0.5, 49);
    
    
//    [self.resetButton setGradientHorizontal:@[[UIColor colorWithHex:0xFFCF16 alpha:1.0],[UIColor colorWithHex:0xFF9002  alpha:1.0]]];
//    [self.completeButton setGradientHorizontal:@[[UIColor colorWithHex:0xFF7700 alpha:1.0],[UIColor colorWithHex:0xFF4900 alpha:1.0]]];
}


#pragma mark - Method
- (void)configureUI {
    [self addSubview:self.mainView];
    [self addSubview:self.backView];
    [self.backView addSubview:self.tableView];
    [self.backView addSubview:self.completeButton];
    [self.backView addSubview:self.resetButton];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissSelf)];
    [self.mainView addGestureRecognizer:tapGesture];
    
    UITapGestureRecognizer *tapKeyBoard = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoardWithGesture:)];
    [self.tableView addGestureRecognizer:tapKeyBoard];
}

- (void)hideKeyBoardWithGesture:(id)sender {
    [self endEditing:YES];
}

- (void)showAnimation {
    self.backView.frame = CGRectMake(self.width, 0, 280, self.height);
    self.alpha = 0.3;
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.35
                          delay:0.0
         usingSpringWithDamping:0.9
          initialSpringVelocity:6.0
                        options:UIViewAnimationOptionCurveEaseIn animations:^{
                            weakSelf.backView.frame = CGRectMake(weakSelf.width - 280, 0, 280, self.height);
                            weakSelf.alpha = 1.0;
                            
                        } completion:^(BOOL finished) {
                            
                        }];
}

- (void)hideAnimation {
    self.backView.frame = CGRectMake(self.width - 280, 0, 280, self.height);
    self.alpha = 1.0;
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.backView.frame = CGRectMake(weakSelf.width, 0, 280, weakSelf.height);
        weakSelf.alpha = 0.0;
    } completion:^(BOOL finished) {
        [weakSelf removeSelf];
    }];
}

- (void)dismissSelf {
    [self hideAnimation];
}

- (void)removeSelf {
    [self removeFromSuperview];
}

#pragma mark - Action
- (void)buttonClick:(UIButton *)sender {
    if (self.block) {
        self.rightModel.minPrice = self.textCell.minTextField.text;
        self.rightModel.maxPrice = self.textCell.maxTextField.text;
        self.block(self.rightModel);
    }
    [self dismissSelf];
}

- (void)resetButtonClick:(UIButton *)sender {
    if (self.block) {
        self.rightModel.minPrice = self.textCell.minTextField.text = @"";
        self.rightModel.maxPrice = self.textCell.maxTextField.text = @"";
        [self.rightModel resetSelect];
        [self.tableView reloadData];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.rightModel.attributeArr.count + 1; //self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.textCell;
    } else {
        FiltrateAttributeItemCell *itemCell = [tableView dequeueReusableCellWithIdentifier:@"itemCell" forIndexPath:indexPath];
        [itemCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        FiltrateFirstModel *firstModel = [self.rightModel.attributeArr objectAtIndex:indexPath.section - 1];
        [itemCell setValueWithFirstModel:firstModel];

        itemCell.block = ^(NSInteger index, BOOL isSelect) {
            FiltrateSecondModel *secondModel = [firstModel.secondList objectAtIndex:index];
            secondModel.isSelect = isSelect;
        };
        
        return itemCell;
        
    }
    return [[UITableViewCell alloc] init];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 48 + 10 + 10;
    } else {
        FiltrateFirstModel *firstModel = [self.rightModel.attributeArr objectAtIndex:indexPath.section - 1];
        return [FiltrateAttributeItemCell getHeightWithFirstModel:firstModel];
    }
    return UITableViewAutomaticDimension;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    FiltrateSectionTitleView *titleView = [[FiltrateSectionTitleView alloc] init];
    
    if (section == 0) {
        [titleView setState:FiltrateSectionStateForNone];
        [titleView setValueWithTitle:@"价格区间"];
        return titleView;
    }
    
    FiltrateFirstModel *firstModel = [self.rightModel.attributeArr objectAtIndex:section - 1];
    [titleView setValueWithTitle:firstModel.title];
    
    if (firstModel.isShow) {
        [titleView setState:FiltrateSectionStateForOpen];
    } else {
        [titleView setState:FiltrateSectionStateForRetract];
    }
    
    __weak typeof(self) weakSelf = self;
    titleView.block = ^{
        firstModel.isShow = !firstModel.isShow;
        
        // 适配iOS11
        if (@available(iOS 11.0, *)) {
            [self.tableView performBatchUpdates:^{
                [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
            } completion:^(BOOL finished) {
                
            }];
        } else {
            [self.tableView beginUpdates];
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView endUpdates];
        }
        
        
    };

    return titleView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if ([string isEqualToString:@"."] && [textField.text containsString:@"."]) {
        return NO;
    } else {
        return YES;
    }
    return YES;
}

#pragma mark - Getters
- (UIView *)mainView {
    if (!_mainView) {
        _mainView = [[UIView alloc] init];
    }
    return _mainView;
}

- (UIView *)backView {
    if (!_backView) {
        _backView = [[UIView alloc] init];
        _backView.backgroundColor = [UIColor whiteColor];
    }
    return _backView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [_tableView registerClass:[FiltrateAttributeItemCell class] forCellReuseIdentifier:@"itemCell"];
        [_tableView setMj_insetT:40];
        [_tableView clearExtendCellLine];
    }
    return _tableView;
}

- (UIButton *)completeButton {
    if (!_completeButton) {
        _completeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_completeButton setTitle:@"完成" forState:UIControlStateNormal];
        [_completeButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_completeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
        [_completeButton setBackgroundColor:[UIColor ThemeColor]];
    }
    return _completeButton;
}

- (UIButton *)resetButton {
    if (!_resetButton) {
        _resetButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_resetButton setTitle:@"清空" forState:UIControlStateNormal];
        [_resetButton addTarget:self action:@selector(resetButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_resetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_resetButton setBackgroundColor:[UIColor colorWithHex:0xFFCF16 alpha:1.0]];
    }
    return _resetButton;
}

- (NSMutableArray *)configureTestData {
    NSMutableArray *listArr = [NSMutableArray array];
    for (NSInteger i = 0; i < 5; i++) {
        FiltrateFirstModel *firstModel = [[FiltrateFirstModel alloc] init];
        firstModel.title = @"哈哈";
        firstModel.isShow = NO;
        NSMutableArray *arr = [NSMutableArray array];
        for (NSInteger j = 0; j < 11; j++) {
            FiltrateSecondModel *secondModel = [[FiltrateSecondModel alloc] init];
            secondModel.title = @"这是";
            [arr addObject:secondModel];
        }
        firstModel.secondList = arr;
        
        [listArr addObject:firstModel];
    }
    return listArr;
}



@end
